<template>
  <div>
    <div v-show="!selectServerShow">
      <div style="width: 2.12rem; height: 0" ref="heightElePadding"></div>
      <!--top-->
      <div class="top-header border-bottom fixed-top">
        <div class="top-back">
          <a href="javascript:history.go(-1)">返回</a>
        </div>
        <h2 class="f36 color-000">{{query.gameName}}</h2>
        <div class="top-right">
          <a href="/index.html" class="back-home"></a>
        </div>
      </div>
       <!--风控警告提示  -->
     
     <FkRemind class="mt-97"></FkRemind>
    <!-- 交易类型 --><!-- mt-97 -->
      <div class="p-30 bg-fff  f30 border-bottom fw Mmt-175">
        <span class="f32 span-icon-xinhao color-000">交易类型</span>
      </div>
      <!--     商品类型      -->
      <div class="px-30 pt-30 pb-10 bg-fff border-bottom publish-type new-publish-type f30 clearfix fw">
        <ul>
          <li v-for="item in goodsTypes"
              :class="{selected: checked.goodsType.goodsType == item.goodsType}"
              @click="changeGameType(item)"
              class="border mb-20 fl color-000">{{item.goodsTypeName}}
          </li>
        </ul>
      </div>
      <div class="p-30 bg-fff border-top mt-20 f30 border-bottom fw">
        <span class="f32 span-icon-xinhao color-000">平台</span>
      </div>
      <!--  平台  -->
      <div class="px-30 pt-30 pb-10 bg-fff border-bottom publish-type new-publish-type f30 clearfix fw">
        <ul>
          <li v-for="item in gamePlants"
              :class="{selected: checked.gamePlant.id === item.id}"
              @click="changePlant(item)"
              class="border mb-20 color-000 fl">{{item.name}}
          </li>
        </ul>
      </div>
      <div v-show="!error" class="p-30 bg-fff border-top mt-20 f30 border-bottom fw" @click="selectServerShow = true">
        <span class="f32 color-000 span-icon-xinhao fl">所属服务器</span>
        <span class="fr f32 color-000 span-icon-toRight">{{showServer}}</span>
      </div>
      <!--提示-->
      <div class="contaner-qq fw" v-if="!showServer.length && showHint">
        <p class="f24">请选择所属服务器</p>
      </div>
      <div class="clearfix bg-fff fw mt-20"
           v-if="showQuickSell && checked.goodsType && checked.goodsType.goodsType === TYPE.ACCOUNT && checkedAll">
        <div class="order-container f30 border-top border-bottom select-kjfb">
          <span class="sec-title fontwgh">快捷发布</span>
          <span class="f24 color-666 exp"><!--<i class="wenhao"></i>-->专业客服帮您截图，商品更易出售</span>
          <div class="button-switch fr">
            <label class="label-switch">
              <input type="checkbox" v-model="isQuick">
              <div class="checkbox"></div>
            </label>
          </div>
        </div>
      </div>
      <div class="release fw mt-20">
        <!--灰色用rgb(187, 187, 187)；选中用class='bg-f54'-->
        <a>
          <input type="button" value="下一步" @click="next()" :class="{'bg-f54': !error}">
        </a>
      </div>
      <div class="text-right proclo fw px-30 py-15 ">
        <!--<a class="f28 color-06c" href="javascript:void(0)" @click="sellRuleShow = true">发布流程</a>-->
      </div>
      <!--发布流程-->
      <div class="process-main " v-show="sellRuleShow">
        <div class="top-header border-bottom">
          <div class="top-back">
            <a @click="sellRuleShow = false" class="goBack">返回</a>
          </div>
          <h2 class="f36 color-000">商品发布流程</h2>
        </div>
        <div class="process-conn">
          <ul>
            <li>
              <div class="pro-left pro-left-bj"><span class="hover">1</span></div>
              <div class="pro-right">
                <i class="prico"></i>
                <h2>卖家提交帐号登录信息</h2>
                <p>需2分钟</p>
              </div>
            </li>
            <li>
              <div class="pro-left"><span>2</span></div>
              <div class="pro-right">
                <i class="prico"></i>
                <h2>5173客服登录游戏审核帐号</h2>
                <p>需5分钟</p>
              </div>
            </li>
            <li>
              <div class="pro-left"><span>3</span></div>
              <div class="pro-right">
                <i class="prico"></i>
                <h2>发布成功，等待买家购买</h2>
              </div>
            </li>
            <li>
              <div class="pro-left"><span>4</span></div>
              <div class="pro-right" id="seller-help4">
                <i class="prico"></i>
                <h2>买家购买后，5173客服帮买家绑定密保手机</h2>
                <!--<p><a id="bindingsmb" target="_blank" href="https://aq.qq.com/cn2/mobile_index">点击绑定</a></p>-->
              </div>
            </li>
            <li class="bacder">
              <div class="pro-left"><span>5</span></div>
              <div class="pro-right" id="seller-help5">
                <i class="prico"></i>
                <h2>绑定密保手机成功后，交易成功</h2>
              </div>
            </li>
          </ul>
        </div>
      </div>
    </div>
    <div v-show="selectServerShow">
      <!-- 选择区服 -->
      <v-select-server
         :historyCheckedArr="historyCheckedArr"
         :gameId="gameId"
         :changeSelectServerShow="changeSelectServerShow"
         :gameClients="gameClients"
         :gameServers="gameServers"
         :checked="checked"
         :custom="custom"
         :paddingHeight="paddingHeight"
         :showCustom= false
         @historyClick="historyClick"
         @clearHistory="clearHistory"
         @commitCustomServer="commitCustomServer"
         @clientClick="clientClick"
         @serverClick="serverClick"
      ></v-select-server>
    </div>
  </div>
</template>

<script>
  import {mapActions} from 'vuex';
  import selectServer from './sell_component/select_server.vue';
  import FkRemind from 'components/common/FkRemind';

  /**
   * 1. 获取一级接口
   *   1. 商品类型 2.平台 3. 客户端列表
   * 2. 二级接口
   *   1. 服务器列表
   */
  export default {
    components: {
      'v-select-server': selectServer,
      FkRemind,
    },
    data() {
      return {
        TYPE: {
          ACCOUNT: 2,
          COIN: 3
        },
        showQuickSell: false, // 是否显示快捷发布按钮
        selectServerShow: false, // 是否显示选择区服组件
        sellRuleShow: false, // 是否显示发布流程的提示
        query: this.$route.query, // query
        gameId: this.$route.query.gameId || '', // 游戏Id
        goodsTypes: null, // 游戏类目列表
        gamePlants: null, // 游戏平台列表
        gameClients: null, // 游戏客户端列表
        gameServers: null, // 游戏服务端列表
        isQuick: false, // 是否选中快捷发布
        checked: { // 商品类型，已经选中的区服信息
          goodsType: null,
          gamePlant: null,
          gameClient: null,
          gameServer: null,
        },
        fromName: '',
        historyCheckedArr: [],
        showHint: false, // 是否显示提示
        customServer: null, // 自定义区服
        custom: { // 自定义的区服
          gamePlant: null,
          gameClient: null,
          gameServer: null,
        },
        error: false, // 没有没有配置商品类型或是没有配置游戏平台列表 则为true
        paddingHeight: 0, // 2.12rem  转 px的值
        checkedAll: false,
       
      }
    },
    computed: {
      showServer() {
        if (this.customServer && this.customServer.length > 0)
          return this.customServer
        if (this.checkedAll && this.checked.gameClient && this.checked.gameServer)
          return this.checked.gameClient.name + '/' + this.checked.gameServer.name
        return ''
      }
    },
    watch: {
      fromName(val) {
//        this.init()
      }
    },
    created() {
      this.$indicator.open({
        spinnerType: 'fading-circle'
      })
    },
    mounted() {
      this.paddingHeight = this.$refs['heightElePadding'].offsetWidth
      this.init()
      if (this.$isLocalStorageSupported()) {
        this.$saveBrowseHistory({
          gameId: this.$route.query.gameId,
          gameName: this.$route.query.gameName,
          gameType: '2'
        },'SellBrowseHistory')
      }
    },
    beforeDestroy() {
      this.$indicator.close()
    },
    beforeRouteEnter(to, from, next) {
      next(vm => {
        vm.fromName = from.name
      })
    },
    methods: {
     
      /* 区服浏览记录保存 */
      saveBrowseHistory(p='') {
        if(this.$isLocalStorageSupported()) {
          let checked = this.checked
          //增加浏览记录
          let params = {
            gameId: this.$route.query.gameId,
            gameName: this.$route.query.gameName,
            gameType: '2'
          }
          if (checked.goodsType) {
            params.goodsType =  checked.goodsType.goodsType
            params.typeName = checked.goodsType.goodsTypeName
          }
          if (checked.gamePlant&&p!='goodsType') {
            params.platformId = checked.gamePlant.id
            params.platformName = checked.gamePlant.name
          }
          if (checked.gameClient&&p!='plant'&&p!='goodsType') {
            params.clientId = checked.gameClient.id
            params.clientName = checked.gameClient.name
          }
          if (checked.gameServer) {
            params.serverId = checked.gameServer.id
            params.serverName = checked.gameServer.name
          }
          this.$saveBrowseHistory(params, 'SellBrowseHistory')
        }
      },
      /* 进入下一步 */
      next() {
        if (this.error) return // 没有配置商品类型和平台则无法进入下一步
        this.showHint = true
        /* 区服空校验 */
        if(!this.showServer.length) return
        let checked = this.checked
        if (this.customServer && this.customServer.length > 0) {
          checked = this.custom
        }
        let query = {
          gameName: this.query.gameName, // 游戏名
          gameId: this.gameId, // 游戏id
          plantId: checked.gamePlant.id, // 平台id
          plantName: checked.gamePlant.name, // 平台名
          clientId: checked.gameClient.id, // 客户端id
          serverId: checked.gameServer.id, // 服务器id
          goodsTypeId: this.checked.goodsType.goodsType, // 商品类型id
          goodsTypeName: this.checked.goodsType.goodsTypeName, // 商品类型id
          showServer: checked.gamePlant.name + '/' + this.showServer, // 客户端名/服务器名
          customServer: this.customServer || '', // 自定义区服名
          categoryId: this.checked.goodsType.mainGameGoodsTypeId, // 新大类
          isQuick: this.isQuick ? '1' : undefined  // 是否快捷发布
        }
        if (this.checked.goodsType.goodsTypeName === '游戏币') {
          this.$router.push({name: 'MGSellSetMessageCoin', query})
        } else
          this.$router.push({name: 'MGSellSetMessageAccount', query})
      },
      /* 获取快捷发布开关 */
      getQuickOpen(server, client, plant) {
        if (!plant) plant = this.checked.gamePlant
        this.showQuickSell = false
        // if (this.checked.goodsType.goodsType === this.TYPE.ACCOUNT) // 账号才出发，游戏币不出发
        if (false) // 合并一期临时取消快捷发布，三期或者几期再恢复
          this.$http.post('/m-base-frontend/gameCategoryAutoOpen/getOpen', {
            gameId: this.query.gameId,
            platformId: plant.id,
            regionId: client.id,
            serverId: server.id
          }).then(res => {
            if (res.data.open) {
              this.showQuickSell = true
            }
          })
      },
      /* 历史记录点击 */
      historyClick({item, index}) {
        this.customServer = null // 初始化自定义区服
        this.checked.gameClient = item.client
        this.checked.gameServer = item.server
        this.selectServerShow = false
        this.checkedAll = true
        /* 把这条历史记录顶到第一行 */
        this.clearHistory(index)
        this.saveLocalStorage(item.client, item.server)
      },
      /* 自定义区服提交 */
      commitCustomServer(input) {
        this.selectServerShow = false
        this.customServer = input
        this.isQuick = false // 选择快捷发布初始化
        this.getQuickOpen(this.custom.gameServer, this.custom.gameClient, this.custom.gamePlant)
      },
      /* 商品类型切换 */
      changeGameType(item) {
        this.checked.goodsType = item
        this.checked.gameServer = null
        this.customServer = null
        this.showHint = false
        this.checkedAll = false
        this.saveBrowseHistory('goodsType')
      },
      /* 平台切换 */
      changePlant(item) {
        if (this.checked.gamePlant === item) return
        this.checked.gamePlant = item
        this.checkedAll = false
        this.custom = {}
        this.isQuick = false // 选择快捷发布初始化

        this.saveBrowseHistory('plant')
        this.setGameClient(item)
        /* 获取品台下的历史选择的 客户端和服务器 */
        this.getLocalStorage()
      },
      /* 客户端切换 */
      clientClick(item) {
        this.setGameServers(item)
        this.checked.gameClient = item
        this.saveBrowseHistory()
      },
      /* 服务器切换，服务器选择 */
      serverClick({server, client}) {
        this.customServer = null // 初始化自定义区服
        if (!this.checked.gameServer || this.checked.gameServer.id !== server.id) {
          this.isQuick = false // 选择快捷发布初始化
          this.getQuickOpen(server, client)
        } // 获取开捷发布开关
        this.checked.gameServer = server // 选择的服务器
        this.checked.gameClient = client // 选择的客户端
        this.selectServerShow = false // 关闭选择客户端&服务器组件
        this.checkedAll = true // 表示条件选择完毕
        /* 保存到LS中 */
        //console.log('_____ serverClick', this.checked.gameClient, this.checked.gameServer)
        let turnClient = {id: this.checked.gameClient.id, name: this.checked.gameClient.name}
        let turnServer = {id: this.checked.gameServer.id, name: this.checked.gameServer.name}
        this.saveLocalStorage(turnClient, turnServer)
        this.saveBrowseHistory()
      },
      /* 清除历史记录 */
      clearHistory(index) {
        if (this.$isLocalStorageSupported()) {
          const key = 'MG_SELL_HISTORY'
          const saveKey = this.gameId + '&' + this.checked.gamePlant.id
          let history = localStorage.getItem(key) ? JSON.parse(localStorage.getItem(key)) : {}
          history[saveKey] = this.historyCheckedArr.filter((v, i) => i !== index)
          localStorage.setItem(key, JSON.stringify(history))
          this.getLocalStorage()
        }
      },
//      /* 存储到localStorage */
      saveLocalStorage(client, server) {
        if (this.$isLocalStorageSupported()) {
          const key = 'MG_SELL_HISTORY' // LS中的key值
          const saveKey = this.gameId + '&' + this.checked.gamePlant.id // 键名  游戏id+平台id
          let history = localStorage.getItem(key) ? JSON.parse(localStorage.getItem(key)) : {} // 获取历史值
          if (!history[saveKey]) history[saveKey] = [] // 如果改 平台下没有记录创建新的
          // 如果历史上已存在一样的记录，则删除
          history[saveKey] = history[saveKey].filter(v => !(v.server.id === server.id && v.client.id === client.id))
          history[saveKey].unshift({client, server}) // 把最新的记录放在第一个
          if (history[saveKey].length > 10) history[saveKey].pop() // 如果条数大于10条则删除
          localStorage.setItem(key, JSON.stringify(history)) // 保存到LS
          this.getLocalStorage()
        }
      },
      /* 获取本地存储 */
      getLocalStorage() {
        if (this.$isLocalStorageSupported()
          && localStorage.getItem('MG_SELL_HISTORY')) {
          this.historyCheckedArr = JSON.parse(localStorage.getItem('MG_SELL_HISTORY'))[this.gameId + '&' + this.checked.gamePlant.id] || []
        } else
          this.historyCheckedArr = []
      },
      /* 获取商品类型和平台 */
      init() {
        Promise.all([
          /* 获取游戏类型 */
          this['getGoodsTypes']({gameId: this.gameId}).then(list => {
            if (list.length === 0) {
              return 'err'
            }
            this.goodsTypes = list
            this.checked.goodsType = list[0]
          }),
          /* 获取平台 */
          this['getGamePlants']({gameId: this.gameId}).then(list => {
            if (list.length === 0) {
              return 'err'
            }
            this.gamePlants = list
            this.checked.gamePlant = list[0]
            /* 获取客户端 */
            this.setGameClient(list[0])
            this.getLocalStorage() // 获取历史记录
          })
        ]).then(([typeErr, plantErr]) => {
          /* 商品类型为空 或 是平台为空 不能发布 */
          if (typeErr || plantErr)
            this.error = true
            this.$indicator.close()
          if (typeErr) {
            this.$toast('该游戏没有配置游戏类型，无法发布商品')
          } else if (plantErr) {
            return this.$toast('该游戏没有配置平台，无法发布商品')
          }

          if (this.$route.query.goodsType) {
            this.checked.goodsType = {goodsType:this.$route.query.goodsType, goodsTypeName:this.$route.query.goodsTypeName}
          }
          if (this.$route.query.goodsType&&this.$route.query.platformId) {
            this.checked.gamePlant = {id:this.$route.query.platformId, name:this.$route.query.platformName}
            this['getGameClients']({gameId: this.gameId, platformId: this.$route.query.platformId}).then(list => {
              this.gameClients = list
            })
          }
          if (this.$route.query.goodsType&&this.$route.query.platformId&&this.$route.query.clientId) {
            this.checked.gameClient = {id:this.$route.query.clientId, name:this.$route.query.clientName}
            this.selectServerShow = true
          }
          if (this.$route.query.goodsType&&this.$route.query.platformId&&this.$route.query.clientId&&this.$route.query.serverId) {
            this.checked.gameServer = {id:this.$route.query.serverId, name:this.$route.query.serverName}
            this.checkedAll = true
            this.selectServerShow = false
            this.getQuickOpen(this.checked.gameServer, this.checked.gameClient, this.checked.gamePlant)
          }
        })
      },
      /* 获取并配置客户端列表 */
      setGameClient(plant) {
        this['getGameClients']({gameId: this.gameId, platformId: plant.id}).then(list => {
          this.gameClients = list
          /* 测试代码 */
          this.checked.gameClient = list[0]
          this.setGameServers(list[0])
        })
      },
      /* 获取并配置服务端列表 */
      setGameServers(client) {
        this.gameServers = null
        if (client)
          this['getGameServers']({aid: client.id, gameId: this.gameId}).then(list => {
            this.$indicator.close()
            this.gameServers = list
            if (this.custom.gameServer && this.custom.gamePlant.id !== this.checked.gamePlant.id) return
            let customGameServer = list.filter(v => v.name === '全区全服')[0]
            if (customGameServer) // 自定义区服归属于全区全服
              this.custom = {
                gamePlant: this.checked.gamePlant,
                gameClient: this.checked.gameClient,
                gameServer: customGameServer,
              }
//            console.log(this.custom)
            /* 测试代码 */
//            this.checked.gameServer = list[0]
//            this.checkedAll = true
          })
        else {
          this.$indicator.close()
          this.gameServers = []
        }
      },
      /* 关闭区服选择 */
      changeSelectServerShow() {
        this.selectServerShow = false
      },
      _copy(obj) {
        return JSON.parse(JSON.stringify(obj))
      },
      ...mapActions([
        'getGamePlants', // 获取游戏平台列表
        'getGoodsTypes', // 获取商品类型
        'getGameClients', // 获取客户端列表
        'getGameServers', // 获取服务端列表
      ])
    }
  }
</script>
<style scoped>
  .bg-f54 {
    background-color: #f75e46 !important;
  }

</style>
